<?php

// Data cache for the all client

class Cache
{
    public static $client = null;

    public static function initClient()
    {
        static::$client = new App\GlobalData\Client('127.0.0.1:2207');
    }

    public static function getWaitingDialogs()
    {
        return static::$client->getWaitingDialogs();
    }

    public static function getOnlineServer()
    {
        return static::$client->getOnlineServer();
    }

    public static function getDialogByUserId($user_id)
    {
        return static::$client->getDialogByUserId($user_id);
    }

    public static function isUserBanned($user_id)
    {
        return static::$client->isUserBanned($user_id);
    }

    // 判断会话是否存在
    public static function dialogExists($user_id)
    {
        return static::$client->dialogExists($user_id);
    }

    // 创建新的待接入会话
    public static function create($payload)
    {
        $time_now = time();
        $dialog = $payload;
        $dialog['unread'] = 1;
        $dialog['banned_at'] = null;
        $dialog['expire_time'] = $time_now + intval(config('DIALOG_EXPIRES'));
        $dialog['server_id'] = 0;
        $dialog['content'] = [];
        $dialog['content'][] = ['role' => 'user', 'content' => $payload['content'], 'time' => $time_now, 'is_auto' => 0];

        static::$client->setDialog($payload['user_id'], $dialog);
        $dialog['content'] = serialize($dialog['content']);
        return $dialog;
    }

    public static function checkExpire()
    {
        $dialog_ids = static::$client->checkExpire();
        if (is_array($dialog_ids)) {
            \App\Models\KfDialog::whereIn('id', $dialog_ids)->update(['status' => 'finished']);
        }
    }

    public static function disable($dialog)
    {
        return static::$client->setBannedDialog($dialog['user_id'], time() + config('BANNED_EXPIRES'));
    }

    //
    public static function bindServerClientId()
    { }

    public static function __callStatic($method, $arguments)
    {
        return static::$client->$method(...$arguments);
    }
}
